<?php
/**
 * UserForm 
 * 
 * Bocheng Chen, 28.08.2012
 * 
 * LBB Solutions Oy 版权所有 @ 2012
 */
class UserForm extends CActiveRecord
{
	public $password_new;
	public $password_new_repeat;
	
	/**
	 * Returns the static model of the specified AR class.
	 * @return ShopProfile the static model class
	 */
	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return 'tbl_user_account';
	}

	/**
	 * Declares the validation rules.
	 * The rules state that password, new_password, new_password_repeat is required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			// fields are required
			array('email', 'required', 'on'=>'settings'),
			array('email', 'email', 'on'=>'settings', 'allowEmpty'=>false, 'checkMX'=>true),
			
			// fires for password model
			array('password_new, password_new_repeat', 'required', 'on'=>'password'),
			array('password', 'valid_current_password', 'on'=>'password'),// password needs to be authenticated on changing password
			array('password_new_repeat', 'compare', 'compareAttribute'=>'password_new', 'on'=>'password'),
			
			array('email, name, mobile, lang, gender', 'safe'),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'name' => BUtils::T('your_name_lbl'),
			'email' => BUtils::T('email_address_lbl'),
			'mobile' => BUtils::T('mobile_number_lbl'),
			'lang' => BUtils::T('prefer_language_lbl'),
		);
	}
	
	/**
	 * Authenticates the password.
	 * This is the 'valid_current_password' validator as declared in rules().
	 */
	public function valid_current_password($attribute, $params) {
		if (!$this->hasErrors()) {
			$sql_user = 'SELECT password, id, status FROM tbl_user_account WHERE id=:id LIMIT 1';
			//fetch password and username
			$connection = Yii::app()->db;
			$command = $connection->createCommand($sql_user);
			$row = $command->queryRow(true, array(':id' => Yii::app()->user->id));
			$connection->active = false;
			
			if (empty($row['password'])) {
				return;//if null, then don't check the password.
			}
			
			$pasword_in_db = BUtils::Hash32(md5($this->password));
			if ($row['password'] === $pasword_in_db) {
				return;
			} else {
				$this->addError('password', Yii::t('app', 'Password is incorrect!'));
				return;
			}
		}
	}
}
